package com.android.newsreader;

import java.util.List;

import com.db4o.query.Predicate;

import android.content.Context;

/**
* Class for persisting RSSItem objects to db4o db
*/
public class RSSChannelProvider extends Db4oHelper {
	
	private static RSSChannelProvider mProvider = null;

    public RSSChannelProvider(Context ctx) {
                  super(ctx);
    }

    public static RSSChannelProvider getInstance(Context ctx) {
                  if (mProvider == null)
                                mProvider = new RSSChannelProvider(ctx);
                  return mProvider;
    }

    /**
     * Store rssChannel in db
     * @param rssChannel rssChannel to be stored
     */
    public void store(RSSChannel rssChannel) {
                  db().store(rssChannel);
    }

    /**
     * Delete rssChannel from db
     * @param rssChannel rssChannel to be deleted
     * @throws Exception
     */
    public void delete(RSSChannel rssChannel) throws Exception {
    	List <RSSChannel>itemsToDelete = find(rssChannel);
    	
    	if (itemsToDelete.size() > 0)
            db().delete(itemsToDelete.get(0));
    	else
    		throw new Exception();
    }

    /**
     * Retrieve all RSSChannels from database
     * @return a list of retrieved RSSChannels
     */
    public List <RSSChannel>findAll() {
                  return db().query(RSSChannel.class);
    }
    
    /**
     * Retrieves all RSSChannels from db similar
     * to provided RSSChannel
     * @param rssChannel template RSSChannel
     * @return list of retrieved channels
     */
    public List <RSSChannel>find(RSSChannel rssChannel) {
        return db().queryByExample(rssChannel);
    }
    
    /**
     * Retrieves all RSSChannels from db with a
     * specified channel name
     * @param channelName channel name to query by
     * @return list of retrieved channels
     */
    public List <RSSChannel>findByName(final String channelName) {
    	List <RSSChannel> channels = db().query(new Predicate<RSSChannel>() {
    		public boolean match(RSSChannel channel) {
    			return channel.getName().equalsIgnoreCase(channelName);
    		}
    	});
    	
    	return channels;
    
    }
    
    
    
}
